package com.thx.common.orm;

import com.thx.common.orm.model.PropertyVal;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 模版Dao.
 * 
 * @author 贾红磊
 */
@Repository
public class PropertyValDao extends HibernateBaseDao<PropertyVal> {

  /**
   * 按属性 id 查询.
   */
  public List<PropertyVal> findByPropertyId(String propertyId) {
    String hql = "from PropertyVal where propertyId = ?";
    Query query = createQuery(hql, propertyId);
    List<PropertyVal> list = query.list();
    return list;
  }

  /**
   * 按属性 id 和实体 id 查询.
   */
  public List<PropertyVal> findByPropertyIdAndEntityId(String propertyId, String entityId) {
    String hql = "from PropertyVal where propertyId = ? and entityId = ?";
    Query query = createQuery(hql, new Object[] {propertyId, entityId});
    List<PropertyVal> list = query.list();
    return list;
  }

  /**
   * 按实体 id 删除.
   */
  public void delByEntityId(String entityId) {
    String hql = "delete from PropertyVal where entityId = ?";
    Query query = createQuery(hql, entityId);
    query.executeUpdate();
  }

  /**
   * 按实体 id 和 租户 id 删除.
   */
  public void delByTenantIdAndEntity(String tenantId, String entityId) {
    String sql = "delete from e_property_val where entity_id = ? and "
        + "property_id in (select p.id from e_template t, e_property p "
        + "where t.tenant_id = ? and p.template_id = t.id)";
    SQLQuery query = createSqlQuery(sql, new Object[] {entityId, tenantId});
    query.executeUpdate();
  }

}
